//
//  ChatViewController.m
//  TIMChat
//
//  Created by AlexiChen on 16/2/23.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ChatViewController.h"
#import <ReactiveCocoa.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImage+WebP.h"
#import "MyChatToolBarView.h"
#import "MyUIDefine.h"
#import "MyMoreView.h"
#import "ChatTableViewCell.h"
#import <AVFoundation/AVFoundation.h>

#import "KeyboardView.h"
#import "GiftModel.h"
#import "TXYUploadManager.h"
#import "UIViewController+Layout.h"
#import "NSString+Ext.h"
#import <AVFoundation/AVAsset.h>

#import <AVFoundation/AVAssetImageGenerator.h>

#import <AVFoundation/AVTime.h>
#import <MediaPlayer/MediaPlayer.h>
#import "YFGIFImageView.h"
#import "SkyLabelWaitingView.h"
#import "CallMakeViewController.h"
#import "UserInfoModel.h"
#import "HomeCallModel.h"

#import <UIViewController+TopViewController.h>
#import "XLHTTPSessionManager+Camgirl.h"
#import "XLHTTPSessionManager+Analytics.h"
#import "XLPersonPageViewController.h"
#import "TopUpViewController.h"
#import <ZipArchive.h>
#import "XLChatSettingVC.h"
#import "XLMakeVoiceChatVC.h"

//#import "BMHGroupInformationVController.h"
//#import "CallRecvViewController.h"
//#import "WaitReciveViewController.h"
#define DECLARE_WEAK_SELF __typeof(&*self) __weak weakSelf = self
#define DECLARE_STRONG_SELF __typeof(&*self) __strong strongSelf = weakSelf

//视频存储路径
#define KVideoUrlPath   \
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"VideoURL"]

#define kNavigationColor     [UIColor colorWithRed:((float)((0xf91676 & 0xFF0000) >> 16))/255.0 green:((float)((0xf91676 & 0xFF00) >> 8))/255.0 blue:((float)(0xf91676 & 0xFF))/255.0 alpha:1.0]

@interface ChatViewController ()<KeyboardViewDelegate
>
{
    //    NSString *videoPath;
    
}

@property (nonatomic, strong) UIWindow                       *liwuWindow;
@property (nonatomic, assign) NSInteger                       currentMoney;
@property (nonatomic, assign) NSInteger                       sendMoney;

@property (nonatomic, strong) MyChatToolBarView              *toolBar;
@property (nonatomic, strong) UIImagePickerController        *imagePicker;
@property (nonatomic, strong) KeyboardView                   *keyboardView;
@property (nonatomic, strong) NSMutableArray                 *senderGiftArr;

//视频上传
@property (nonatomic, strong) TXYUploadManager               *uploadVideoManager;
@property (nonatomic, strong) TXYFileUploadTask              *uploadVideoTask;
@property (nonatomic, strong) TXYVideoUploadTaskRsp          *videoResp;

@property (nonatomic, copy  ) NSString                       *persistenceId;
@property (nonatomic, copy  ) NSString                       *bucket;
@property (nonatomic, copy  ) NSString                       *videoSign;

@property (nonatomic, strong) UIImage                        *videoImage;
@property (nonatomic, copy  ) NSString                       *senderNameSTR;
@property (nonatomic, copy  ) NSString                       *videoNameSTR;
@property (nonatomic, copy  ) NSString                       *videoImageSTR;

@property (nonatomic, copy  ) NSString                       *videoPathSTR;
@property (nonatomic, copy  ) NSString                       *videoURL;

//图片上传
@property (nonatomic, strong) TXYUploadManager                *uploadImageManager;
@property (nonatomic, strong) TXYPhotoUploadTask              *uploadPhotoTask;
@property (nonatomic, strong) TXYPhotoUploadTaskRsp           *photoResp;

@property (nonatomic, copy  ) NSString                        *imagepersistenceId;
@property (nonatomic, copy  ) NSString                        *imagebucket;
@property (nonatomic, copy  ) NSString                        *appId;
@property (nonatomic, copy  ) NSString                        *imageSign;
@property (nonatomic, strong) UIImage                         *uploadheadImage;
@property (nonatomic, assign) NSInteger                        imageIndex;
@property (nonatomic, assign) BOOL                             isFrst;
@property (nonatomic, assign) BOOL                             isenter;


//
@property (nonatomic, assign) NSInteger                        index;
@property (nonatomic, strong) YFGIFImageView                  *gifview;
@property (nonatomic, strong) UIImageView                     *gifImageView;
@property (nonatomic, strong) HomeCallModel                   *userInfoModel;

//私聊价格
@property (nonatomic, strong) NSString                         *voiceSwitchValue;
@property (nonatomic, strong) NSString                         *VideoSwitchValue;
@property (nonatomic, strong) NSString                         *isForVoicePrice;
@property (nonatomic, strong) NSString                         *isForVideoPrice;

@property (nonatomic, assign) NSInteger                        Sign;

@property (nonatomic, assign) NSInteger                        chatStatus;
@property (nonatomic, copy  ) NSString                         *errcodeStatus;
//
@property (nonatomic, copy  ) NSString                          *groupUserCount;
@property (nonatomic, assign) BOOL                              isLastmessage;
@property (nonatomic, copy  ) NSString                          *avChatRoomId;
@property (nonatomic, assign) BOOL                               isblack;
@property (nonatomic, assign) BOOL                               giftAnimalFinish;


//上传的视频或图片信息数组
@property (nonatomic, strong) NSMutableArray * mediaArray;
@end

@implementation ChatViewController
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [HelpTool statStartEventId:@"108" eventLabel:@"进入私聊界面"];
    
    
    [[NSUserDefaults standardUserDefaults] setObject:@"no" forKey:@"nowimage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
}

- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    [_receiverKVO unobserveAll];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWith:(IMAUser *)user
{
    if (self = [super init])
    {
        //        self.currentPageId = @"chatpage";
        NSLog(@"userrrr == %@", user.nickName);
        _sendInputStatus = SendInputStatus_notSend;
        _receiver = user;
        //        _isSendMsg = NO;
        [self getUserInfoUserID:user.userId];
    }
    return self;
}

-(void)getUserInfoUserID:(NSString *)userID
{
    kWeakSelf(self);
    [self getIsAnchorWithUserID:userID Complete:^(NSString *isAnchor) {
        weakself.isAnchor_rec = isAnchor;
    }];
}

- (void)addHeaderView
{
    self.headerView = [[ChatHeadRefreshView alloc] init];
}

- (void)onRefresh
{
    __weak ChatViewController *ws = self;
    [_conversation asyncLoadRecentMessage:30 completion:^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
        if (succ)
        {
            [ws onLoadRecentMessage:imamsgList complete:YES scrollToBottom:YES isHeadRefresh:YES];
        }
        
        [ws refreshCompleted];
        [ws layoutHeaderRefreshView];
    }];
}


- (void)addFooterView
{
    // 作空实现
}

- (void)addOwnViews
{
    [super addOwnViews];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _tableView.sectionFooterHeight = 0.f;
    
    CGFloat kToolbarY = CGRectGetMaxY(self.view.bounds) - CHAT_BAR_MIN_H - 2*CHAT_BAR_VECTICAL_PADDING - 50;
    _tableView.frame = CGRectMake(CGRectGetMinX(self.view.bounds), CGRectGetMinY(self.view.bounds), CGRectGetWidth(self.view.bounds), kToolbarY);
    
    [self addChatToolBar];
    
    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPress:)];
    longPressGr.minimumPressDuration = 1.0;
    [_tableView addGestureRecognizer:longPressGr];
    
    
}
-(void)onLongPress:(UILongPressGestureRecognizer *)gesture
{
    
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        CGPoint point = [gesture locationInView:self.tableView];
        
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
        UITableViewCell<TIMElemAbleCell> *cell = [_tableView cellForRowAtIndexPath:indexPath];
        BOOL showMenu = [cell canShowMenu];
        
        if (showMenu)
        {
            if ([cell canShowMenuOnTouchOf:gesture])
            {
                [cell showMenu];
            }
        }
    }
}


- (void)addChatToolBar
{
    CGFloat kToolbarY = CGRectGetMaxY(self.view.bounds) - CHAT_BAR_MIN_H - 2*CHAT_BAR_VECTICAL_PADDING - 50;
    
    _toolbar = [[MyChatToolBarView alloc] initWithFrame:CGRectMake(0, kToolbarY, CGRectGetWidth(self.view.bounds), CHAT_BAR_MIN_H+2*CHAT_BAR_VECTICAL_PADDING + 50) chatType:[_conversation type]];
    _toolbar.delegate = self;
    [self.view addSubview:_toolbar];
    [(MyMoreView *)_toolbar.moreView setDelegate:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _giftAnimalFinish = YES;
    [self showBackButton:NULL];
    [[UITextField appearance] setTintColor:[UIColor darkGrayColor]];
    //    NSLog(@"[BMHAccountManager shareInstance].userInfoModel == %f", [BMHAccountManager shareInstance].userInfoModel.rosecount);
    [self requestData];//美女信息
    [self privateInfo];//私聊价格
    [self getUploadImageSign];
    [self getUploadVidepSign];
    self.fd_interactivePopDisabled = YES;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor blackColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUpdateInputStatus:) name:kUserInputStatus object:nil];
    [UserDefaults setObject:@([_receiver isGroupType]) forKey:@"isnowchat"];
    UITapGestureRecognizer* tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyBoard)];
    [self.tableView addGestureRecognizer:tapAction];
    self.senderGiftArr = [NSMutableArray array];
    [self getFlowerList];
    self.isFrst = YES;
    //初始化万象优图
    _appId = @"10063237";
    //    _bucket = @"redvideo"; //上传视频入口：发表动态：bucket=bucket 发红包视频：bucket=tempvideo
    _bucket = @"tempvideo";
    
    _persistenceId = @"videoID";//自定义,唯一,没有限制
    
    
    _imagebucket = @"bucketimg";
    _imagepersistenceId = @"persistenceId";//自定义,唯一,没有限制persistenceId
    //上传图片总共五步之     第二步 向自己的业务服务器请求 上传image所需要的签名
    //上传图片总共五步之     第三步: 初始化上传工具
    _uploadImageManager = [[TXYUploadManager alloc] initWithCloudType:TXYCloudTypeForImage
                                                        persistenceId:_imagepersistenceId
                                                                appId:_appId];
    _uploadVideoManager = [[TXYUploadManager alloc] initWithCloudType:TXYCloudTypeForFile
                                                        persistenceId:_persistenceId
                                                                appId:_appId];
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(messageChange:) name:@"delateindexPath" object:nil];
    //     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshGiftMessage:)name:@"chatGiftMessage" object:nil];//礼物接收
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickInviteVideoChatCell) name:@"ChatGirlInvitFaceViewCell" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTapPayImage) name:@"onTapPayImage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTapPayVideo) name:@"onTapPayVideo" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tapMessageAvatar:) name:@"tapMessageAvatar" object:nil];
    if ([_receiver isC2CType]) {
        UIButton * inforBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        [inforBtn setImage:[[UIImage imageNamed:@"im_but_yonghu_default.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        inforBtn.imageView.tintColor = [UIColor blackColor];
        [inforBtn addTarget:self action:@selector(inforBtnChatNavAction) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton * chatBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        [chatBtn setImage:[[UIImage imageNamed:@"me_tab_but_shiping_n"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
        chatBtn.imageView.tintColor = [UIColor blackColor];
        [chatBtn addTarget:self action:@selector(moreVideChatVideoAction) forControlEvents:UIControlEventTouchUpInside];
        chatBtn.hidden = YES;
        if ([_receiver.userId isEqualToString:@"10000"]) {
            inforBtn.hidden = YES;
        }
        UIBarButtonItem *inforBtnItem =[[UIBarButtonItem alloc] initWithCustomView:inforBtn];
        UIBarButtonItem *chatBtnItem  =[[UIBarButtonItem alloc] initWithCustomView:chatBtn];
        self.navigationItem.rightBarButtonItems = @[inforBtnItem,chatBtnItem];
        
    }
    
    [self showBackButton:NULL];

    
}


//个人主页
- (void)inforBtnChatNavAction {
    
    XLChatSettingVC *vc = [[XLChatSettingVC alloc] init];
    vc.blackUserId = _receiver.userId;
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)showBackButton:(void (^)(void))clickBlock{
    if ([_receiver isC2CType]) {
        UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
        
        UIImage *backImg = [UIImage imageNamed:@"common_nav_btn_back_n"];
        backImg = [backImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [backButton setImage:backImg forState:UIControlStateNormal];
        
        //        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
        //        titleLab.text = [_receiver showTitle];
        //        titleLab.textAlignment = NSTextAlignmentLeft;
        //        [navView addSubview:backButton];
        //        [navView addSubview:titleLab];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:navView];
        
        @weakify(self);
        [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            if (clickBlock) {
                clickBlock();
            }else{
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
    }else {
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
        
        UIImage *backImg = [UIImage imageNamed:@"common_nav_btn_back_n"];
        backImg = [backImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [backButton setImage:backImg forState:UIControlStateNormal];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
        
        @weakify(self);
        [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            if (clickBlock) {
                clickBlock();
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        
    }
}
- (void)messageChange:(NSNotification *)notification
{
    //    NSLog(@"ddddd ==== %@", notification);
    NSIndexPath *message = notification.object;
    UITableViewCell<TIMElemAbleCell> *cell = [self.tableView cellForRowAtIndexPath:message];
    //    BOOL showMenu = [cell canShowMenu];
    //    NSLog(@"vvvvvvvvvbbbbb == %ld", showMenu);
    //    if (showMenu)
    //    {
    [cell deletIndexPath:message];
    //    }
    [self.tableView reloadData];
    
    
}
-(void)getUploadImageSign
{
    //    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"sign", @"action",@"bucketimg", @"bucketName",nil];
    NSString *userId = [[XLAccountManager shareInstance] model].Id;
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,userId, publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",locationString,@"Timestamp",nat,@"Appsign",userId,@"Userid",@"sign", @"action",@"bucketimg", @"bucketName",nil];
    
    [BMHHTTPSession UploadHeadGET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dic success:^(id  _Nullable JSON) {
        self.imageSign = JSON[@"result"][@"errmsg"];
        
        NSLog(@"服务获取签名======-=-=-----%@", JSON);
        
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    
}
-(void)getUploadVidepSign
{
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    
    
    //    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",@"sign", @"action",@"redvideo", @"bucketName",nil];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"type",locationString,@"Timestamp",nat,@"Appsign",[[NSUserDefaults standardUserDefaults] objectForKey:UserID],@"Userid",@"sign", @"action",@"tempvideo", @"bucketName",nil];
    
    [BMHHTTPSession UploadHeadGET:@"MobileInterface/Video/VideoCloud.ashx" paraments:dic success:^(id  _Nullable JSON) {
        NSLog(@"服务获取vvvv签名======-=-=-----%@", JSON);
        self.videoSign = JSON[@"result"][@"errmsg"];
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

-(void)getFlowerList
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"5", @"type",nil];
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/Gift/GetGiftList" parameters:dic resultClass:nil] subscribeNext:^(id x) {
        [self getSenderGiftArr:x];
    } error:^(NSError *error) {
        
    }];
    
}
- (void)getSenderGiftArr:(NSMutableArray *)arr {
    for (int i = 0; i < arr.count; i++) {
        GiftModel *giftModer = [[GiftModel alloc] initWithDict:arr[i]];
        [self.senderGiftArr addObject:giftModer];
    }
    //    [self.tableView reloadData];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reaciveGiftMessage2:)name:@"videoGiftMessage" object:nil];//新礼物接收
    if ([_receiver isGroupType]) {
        [self setChatTitle];
    } else {
        [self ifisBalack];
    }
    
    _receiverKVO = [FBKVOController controllerWithObserver:self];
    [self configWithUser:_receiver];
    
    //    [_tableView reloadData];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        NSInteger rows = [_tableView numberOfRowsInSection:0];
    //        if (rows > 5) {
    //            [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    //        }
    //    });
    //    if (self.isenter == YES) {
    //        self.isenter = NO;
    //        [_conversation releaseConversation];
    //
    //        __weak ChatViewController *ws = self;
    //        _conversation = [[IMAPlatformxl sharedInstance].conversationMgr msgchatWith:_receiver];
    ////        [_messageList removeAllObjects];
    //        [_tableView reloadData];
    //        _messageList = _conversation.msgList;
    //
    //        [_conversation asyncLoadRecentMessage:30 completion:^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
    //            [_messageList removeAllObjects];
    //            [_messageList insertObjectsFromArray:imamsgList atIndex:0];
    ////            [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:imamsgList.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    //
    //            [_tableView reloadData];
    //
    //            [_tableView endUpdates];
    //
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //                if (imamsgList.count > 3) {
    //                    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:imamsgList.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    //
    //                }
    //
    //            });
    //        }];
    //    _conversation.receiveMsg = ^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
    //        if (self.isenter == YES && [[[NSUserDefaults standardUserDefaults] objectForKey:@"nowimage"] isEqualToString:@"no"]) {
    //            [ws modifySendInputStatus:SendInputStatus_Send];
    //
    //            [ws onReceiveNewMsg:imamsgList succ:succ];
    //            [ws updateMessageList];
    //            TIMElem *meaage = [msg.msg getElem:0];
    //            if ([meaage isKindOfClass:[TIMCustomElem class]]) {
    //                TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
    //                CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    //                if (elemCmd.msgType == 3) {
    //                    if ([elemCmd.giftBubbleImage rangeOfString:@"gif"].location != NSNotFound ) {
    //                        [ws addGifPicWithIndexXX:elemCmd.giftBubbleImage];
    //
    //                    }else {
    //                        [ws addGifImageView:elemCmd.giftMsgImage];
    //
    //                    }
    //
    //                }
    //
    //            }
    //
    //        }
    //
    //    };
    
    //    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"videoGiftMessage" object:nil];//新礼物接收
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
//    NSString *filePath = [self getDirectoryOfDocumentFileWithName:self.videoNameSTR];
//    if (filePath) {
//        [self removeFileAtPath:filePath];
//    }
    
    //    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //    manager.enable = YES;
    //    manager.shouldResignOnTouchOutside = YES;
    //    manager.shouldToolbarUsesTextFieldTintColor = YES;
    //    manager.shouldShowTextFieldPlaceholder = NO;
    //    manager.enableAutoToolbar = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chatDisappear" object:nil];
    
}
#pragma mark *******IM收消息和礼物
- (void)configWithUser:(IMAUser *)user
{
    [_receiverKVO unobserveAll];
    _receiver = user;
    __weak ChatViewController *ws = self;
    _receiverKVO = [FBKVOController controllerWithObserver:self];
    
    [_receiverKVO observe:_receiver keyPaths:@[@"remark", @"nickName"] options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [ws setChatTitle];
    }];
    
    if (_conversation)
    {
        [_conversation releaseConversation];
        _messageList = nil;
        [self reloadData];
    }
    
    _conversation = [[IMAPlatformxl sharedInstance].conversationMgr msgchatWith:_receiver];
    _messageList = _conversation.msgList;
    NSLog(@"_messageList_messageList %ld---%@", _messageList.count,[user userId]);
    
    [_conversation asyncLoadRecentMessage:30 completion:^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
        [ws onLoadRecentMessage:imamsgList complete:succ scrollToBottom:YES isHeadRefresh:NO];
    }];
    
    _conversation.receiveMsg = ^(NSArray *imamsgList, BOOL succ, IMAMsg *msg) {
        
        [ws modifySendInputStatus:SendInputStatus_Send];
        [ws onReceiveNewMsg:imamsgList succ:succ];
        [ws updateMessageList];
        TIMElem *meaage = [msg.msg getElem:0];
        if ([meaage isKindOfClass:[TIMCustomElem class]]) {
            TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
            CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
            if (elemCmd.msgType == 3) {
                if ([elemCmd.giftBubbleImage rangeOfString:@"gif"].location != NSNotFound ) {
                    [ws addGifPicWithIndexXX:elemCmd.giftBubbleImage];
                    
                }else {
                    [ws addGifImageView:elemCmd.giftMsgImage];
                    
                }
                
            }
            
        }
        
    };
    [self addChatSettingItem];
    [self setChatTitle];
    
    // 同步群资料
    if ([user isGroupType])
    {
        [((IMAGroup *)user) asyncUpdateGroupInfo:nil fail:nil];
        [self getGroupMessage];
    }
    
    
}


- (void)reaciveGiftMessage2:(NSNotification *)infor{
    IMAMsg *msg = infor.object;
    [self modifySendInputStatus:SendInputStatus_Send];
    [_messageList addObject:msg];
    NSArray *imamsgList = @[msg];
    [self onReceiveNewMsg:imamsgList succ:YES];
    [self updateMessageList];
    TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
    NSDictionary *giftdic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
    NSString *urlStringMove = elemCmd.giftBubbleImage;
    NSString *urlStringImg = elemCmd.giftMsgImage;
    NSString *idGift = [NSString stringWithFormat:@"%@",giftdic[@"giftId"]];
    CGFloat durition = 0.0;
    if ([idGift integerValue] == 110 || [idGift integerValue] == 111 || [idGift integerValue] == 112) {
        durition =  4.6;
    }else{
        durition = 8.5;
    }
    if (![idGift isEqualToString:@"109"]){//不是么么哒动画
        if (![urlStringMove isKindOfClass:[NSNull class]]&&urlStringMove.length > 0) {//moveimage有数据
            if ([urlStringMove rangeOfString:@"webp"].location != NSNotFound){//读取
                NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                NSString *fileName = [[urlStringMove componentsSeparatedByString:@"/"]lastObject];
                NSString *imageFilePath = [path stringByAppendingPathComponent:fileName];
                NSError * error;
                NSData * data = [NSData dataWithContentsOfFile:imageFilePath options:NSDataReadingMappedIfSafe error:&error];
                if (data) {
                    UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                    UIWindow *window = [UIApplication sharedApplication].keyWindow;
                    [window addSubview:imageV];
                    dispatch_queue_t queueAnimal = dispatch_queue_create("animalQueue", DISPATCH_QUEUE_SERIAL);
                    dispatch_async(queueAnimal, ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            UIImage * image = [UIImage sd_imageWithWebPData:data];
                            imageV.image = image;
                        });
                        sleep(durition);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [imageV removeFromSuperview];
                            _giftAnimalFinish = YES;
                        });
                    });
                    
                }else{
                    NSLog(@"没有拿到数据");
                    [self downloadWebp:urlStringMove time:durition];
                }
            }else{//webp不为空的普通动画
                _giftAnimalFinish = YES;
                [self addGifImageView:urlStringImg];
            }
        }else{//webp为空的普通动画
            
        }
    }else{//么么哒动画
        _giftAnimalFinish = YES;
        [self addGifImageView:urlStringImg];
    }
    dispatch_queue_t queueAnimal = dispatch_queue_create("animalQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queueAnimal, ^{
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"任务执行完毕，回到主线程 thread:%@",[NSThread currentThread]);
        });
        
    });
    
    
}
- (void)downloadWebp:(NSString *)urlString time:(CGFloat)durition{
    dispatch_queue_t queue2 = dispatch_queue_create("queue", NULL);
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:imageV];
    __block UIImage *images;
    dispatch_async(queue2, ^{//开线城下载
        NSError * error;
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString] options:NSDataReadingMappedIfSafe error:&error];
        if (data) {
            
            dispatch_queue_t queueAnimal = dispatch_queue_create("animalQueue", DISPATCH_QUEUE_SERIAL);
            dispatch_async(queueAnimal, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    images = [UIImage sd_imageWithWebPData:data];
                    imageV.image = images;
                });
                sleep(durition);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [imageV removeFromSuperview];
                    _giftAnimalFinish = YES;
                });
            });
            
        }else{
            NSLog(@"惨啦，没有拿到数据");
        }
    });
    dispatch_async(queue2, ^{
        dispatch_sync(dispatch_get_main_queue(), ^{
            imageV.image = images;
            NSLog(@"任务执行完毕，回到主线程 thread:%@",[NSThread currentThread]);
        });
        
    });
}
- (void)loadMember:(NSMutableArray *)members
{
}

- (void)addToMemberDic:(NSArray *)admins others:(NSArray *)otherMembers targetArray:(NSMutableArray *)members
{
    [members addObjectsFromArray:admins];
}
- (void)addGifImageView:(NSString *)gifStr {
    [self.gifImageView removeFromSuperview];
    UIWindow *window = kDeviceWindow;
    self.gifImageView = [[UIImageView alloc]init];
    self.gifImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.gifImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.gifImageView setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    self.gifImageView.backgroundColor=[UIColor clearColor];
    [self.gifImageView sd_setImageWithURL:[NSURL URLWithString:gifStr]];
    self.gifImageView.frame= CGRectMake(window.frame.size.width / 2 - 100, 150, 200, 200);
    [self.view addSubview:self.gifImageView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.gifImageView removeFromSuperview];
        });
    });
}

- (void)addGifPicWithIndexXX:(NSString *)gifStr {
    [self.gifview removeFromSuperview];
    UIWindow *window = kDeviceWindow;
    NSString *gifPath= gifStr;
    self.gifview = [[YFGIFImageView alloc]init];
    self.gifview.backgroundColor=[UIColor clearColor];
    NSData *gifData = [NSData dataWithContentsOfURL:[NSURL URLWithString:gifPath]];
    self.gifview.gifData= gifData;
    self.gifview.frame= CGRectMake(window.frame.size.width / 2 - 100, 150, 200, 200);
    [self.view addSubview:self.gifview];
    [self.gifview startGIF];
    [UIView animateWithDuration:0.5f delay:3 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.gifview.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [self.gifview removeFromSuperview];
    }];
}

- (void)getGroupMessage {

}

- (void)setChatTitle
{
    NSString * title;
    if ([_receiver isGroupType]) {
        IMAGroup *group = (IMAGroup *)_receiver;
        title = [NSString stringWithFormat:@"%@(%@)",[_receiver showTitle],[self.groupUserCount integerValue] > 0 ?self.groupUserCount : @"1"];
        NSLog(@"shifoujieshou === %ld",(long)group.groupInfo.selfInfo.recvOpt);
        NSMutableAttributedString *attri =     [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@(%@) ",[_receiver showTitle],[self.groupUserCount integerValue] > 0 ?self.groupUserCount : @"1"]];
        
        if (group.groupInfo.selfInfo.recvOpt != 0) {
            NSTextAttachment *attch = [[NSTextAttachment alloc] init];
            // 表情图片
            attch.image = [UIImage imageNamed:@"nav_icon_miandarou_default"];
            // 设置图片大小
            attch.bounds = CGRectMake(0, 0, 16, 16);
            
            // 创建带有图片的富文本
            NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
            [attri appendAttributedString:string];
            
        }
        
        // 用label的attributedText属性来使用富文本
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, XQScreenW - 100, 64)];
        titleLab.font = [UIFont systemFontOfSize:18];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.attributedText = attri;
        self.navigationItem.titleView = titleLab;
        
    }else {
        title = [NSString stringWithFormat:@"%@",[_receiver showTitle]];
        if (title.length > 10)
        {
            title = [NSString stringWithFormat:@"%@...", [title substringToIndex:10]];
        }
        
        self.navigationItem.title = title;
        
        //        UIView *titelview = [[UIView alloc] initWithFrame:CGRectMake(144, 0, XQScreenW - 144, 44)];
        //        UIButton *giftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        giftBtn.frame = CGRectMake(XQScreenW - 144 - 74, 0, 44, 44);
        //        [giftBtn setImage:[UIImage imageNamed:@"ic-liwu"] forState:UIControlStateNormal];
        //        [giftBtn addTarget:self action:@selector(moreVideFlowerAction) forControlEvents:UIControlEventTouchUpInside];
        //        [titelview addSubview:giftBtn];
        //        UIButton *videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        videoBtn.frame = CGRectMake(XQScreenW - 144 - 74 - 44, 0, 44, 44);
        //        [videoBtn setImage:[UIImage imageNamed:@"ic-hongbaotu"] forState:UIControlStateNormal];
        //        [videoBtn addTarget:self action:@selector(moreViewMoneyVideoAction) forControlEvents:UIControlEventTouchUpInside];
        //
        //        [titelview addSubview:videoBtn];
        //        UIButton *shiliaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        shiliaoBtn.frame = CGRectMake(XQScreenW - 144 - 74 - 44 - 44, 0, 44, 44);
        //        [shiliaoBtn setImage:[UIImage imageNamed:@"ic-shipin"] forState:UIControlStateNormal];
        //        [shiliaoBtn addTarget:self action:@selector(moreVideChatVideoAction) forControlEvents:UIControlEventTouchUpInside];
        //
        //        [titelview addSubview:shiliaoBtn];
        //
        //        self.navigationItem.titleView = titelview;;
    }
    
}
- (void)onReceiveNewMsg:(NSArray *)imamsgList succ:(BOOL)succ
{
    [_tableView beginUpdates];
    
    NSInteger count = [imamsgList count];
    NSMutableArray *indexArray = [NSMutableArray array];
    NSIndexPath *index;
    for (NSInteger i = 0; i < count; i++)
    {
        NSInteger idx = _messageList.count + i - count;
        index = [NSIndexPath indexPathForRow:idx inSection:0];
        [indexArray addObject:index];
        NSLog(@"~~~~~~~~~~~~~~~~%ld,%@",idx,indexArray);
        
    }
    [_tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationBottom];
    [_tableView endUpdates];
    [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    CGFloat delta =_tableView.contentSize.height - _tableView.contentOffset.y - 60;
    
    //刚好能完整看到footer的高度
    
    CGFloat sawFooterH = _tableView.height -self.tabBarController.tabBar.height ;
    
    // 2.如果能看见整个footer
    NSLog(@"sawFooterHsawFooterH == %f ---- %f",delta, sawFooterH);
    if (delta <= (sawFooterH - 0)) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"nowimage"] isEqualToString:@"no"]) {
                [self updateOnSendMessage:imamsgList succ:YES];
                
            }
        });
        
    }
}

//当消息量过大时，需要清理部分消息，避免内存持续增长
- (void)updateMessageList
{
    if (_messageList.count > 1000)
    {
        DebugLog(@"_messageList.count > 1000");
        int rangLength = 100;
        NSRange range = NSMakeRange(_messageList.count-rangLength, rangLength);
        [_messageList subArrayWithRange:range];
        [_tableView reloadData];
        
    }
}

- (void)onLoadRecentMessage:(NSArray *)imamsgList complete:(BOOL)succ scrollToBottom:(BOOL)scroll isHeadRefresh:(BOOL)isHeadRefresh {
    if (succ) {
        if (imamsgList.count > 0) {
            
            //            [_tableView beginUpdates];
            //            NSMutableArray *ar = [NSMutableArray array];
            //            for (NSInteger i = 0; i < imamsgList.count; i++) {
            //                [ar addObject:[NSIndexPath indexPathForItem:i inSection:0]];
            //            }
            //            [_tableView insertRowsAtIndexPaths:ar withRowAnimation:UITableViewRowAnimationNone];
            //            [_tableView endUpdates];
            [_tableView reloadData];
            
            if (scroll) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (isHeadRefresh) {
                        NSIndexPath *last = [NSIndexPath indexPathForRow:imamsgList.count inSection:0];
                        [self.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionTop animated:NO];
                    } else {
                        NSIndexPath *last = [NSIndexPath indexPathForRow:imamsgList.count - 1 inSection:0];
                        [self.tableView scrollToRowAtIndexPath:last atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                    }
                });
            }
        }
    }
}

- (void)layoutRefreshScrollView
{
    CGFloat kToolbarY = CGRectGetMaxY(self.view.bounds) - CHAT_BAR_MIN_H - 2*CHAT_BAR_VECTICAL_PADDING;
    
    // do nothing
    _tableView.frame = CGRectMake(CGRectGetMinX(self.view.bounds), CGRectGetMinY(self.view.bounds), CGRectGetWidth(self.view.bounds), kToolbarY);
    _toolbar.frame = CGRectMake(0, kToolbarY, CGRectGetWidth(self.view.bounds), CHAT_BAR_MIN_H+2*CHAT_BAR_VECTICAL_PADDING + 50);
}


- (void)addChatSettingItem
{
    DebugLog(@"子类实现");
}

- (void)onClickChatSetting
{
    DebugLog(@"在子类中实现");
}

// 加载历史信息
- (void)loadHistotyMessages
{
    
}

// 添加收到的信息
- (void)appendReceiveMessage
{
    
}

///==========================
#pragma mark - MyChatToolBarViewDelegate

- (void)updateOnSendMessage:(NSArray *)msglist succ:(BOOL)succ
{
    if (self.isback == YES) return;
    if (msglist.count)
    {
        
        NSInteger index = [_messageList indexOfObject:msglist.lastObject];
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}
- (void)ifisBalack {
    @weakify(self);
    [[[XLHTTPSessionManager sharedXIUQUManager] fetchGetBlacklistBuserId:[_receiver userId] UserId:[[XLAccountManager shareInstance] model].Id type:@"3"] subscribeNext:^(id _Nullable responseObject) {
        @strongify(self);
        id resultObj = [responseObject objectForKey:@"result"];
        NSLog(@"laheiiiii == %@",resultObj);
        NSInteger errCode = [resultObj[@"errcode"] integerValue];
        if (errCode == 1) {
            _isblack = YES;
            
        }else {
            _isblack = NO;
        }
        [self.view reloadInputViews];
    } error:^(NSError *error) {
        
    }];
    
}

#pragma mark - 发送消息
- (void)sendMsg:(IMAMsg *)msg
{
    if (_isblack) {
        [HelpTool startTipViewWithText:@"发送失败,已成为黑名单用户" duration:2 type:kTipViewTypeNone];
    }
    
    else {
        if (msg)
        {
            //        _isSendMsg = YES;
            [_tableView beginUpdates];
            __weak ChatViewController *ws = self;
            NSArray *newaddMsgs = [_conversation sendMessage:msg completion:^(NSArray *imamsglist, BOOL succ, int code) {
                DebugLog(@"sendmessage end");
                [ws updateOnSendMessage:imamsglist succ:succ];
                if (!succ)
                {
                    if (code == kSaftyWordsCode)
                    {
                    }
                }
                //添加扣费(发送成功返回)
                if (succ) {
                //扣费 是否是主播
                    if ([[XLAccountManager shareInstance].model.IsAnchor isEqualToString:@"0"]) {
                        [self setSendContentWithStyle:msg];
                    }
                
                }
            }];
            if (newaddMsgs.count != 0) {
                [self showMsgs:newaddMsgs];
                
            }else {
                [HelpTool startTipViewWithText:@"发送失败" duration:1 type:kTipViewTypeNone];
            }
            TIMElem *meaage = [msg.msg getElem:0];
            if ([meaage isKindOfClass:[TIMCustomElem class]]) {
                TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
                CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
                if (elemCmd.msgType == 3) {
                    if ([elemCmd.giftBubbleImage rangeOfString:@"gif"].location != NSNotFound ) {
                        [self addGifPicWithIndexXX:elemCmd.giftBubbleImage];
                        
                    }else {
                        [self addGifImageView:elemCmd.giftMsgImage];
                        
                    }
                    
                }else {
                    
                }
            }
            if (self.isFrst == YES) {
                if ([meaage isKindOfClass:[TIMTextElem class]]) {
                    
                    [self recodeChatLoadwithType:@"1"];
                }else if ([meaage isKindOfClass:[TIMVideoElem class]]){
                    [self recodeChatLoadwithType:@"2"];
                    
                }else if ([meaage isKindOfClass:[TIMCustomElem class]]){
                    TIMCustomElem *elem = (TIMCustomElem *)[msg.msg getElem:0];
                    CustomElemCmd *elemCmd = [CustomElemCmd parseCustom:(TIMCustomElem *)elem];
                    
                    [self recodeChatLoadwithType:@"2"];
                    if (elemCmd.msgType == 5) {
                        [self recodeChatLoadwithType:@"4"];
                        
                    }else {
                        [self recodeChatLoadwithType:@"3"];
                        
                    }
                    
                }else {
                    [self recodeChatLoadwithType:@"1"];
                    
                }
                
            }
        }
        
    }
    
    if(self.mediaArray.count > 0)
    {
        HXPhotoModel * model = self.mediaArray[0];
        [self getResourcesToUploading:model.asset AndImage:model.thumbPhoto];
        [self.mediaArray removeObjectAtIndex:0];
        NSLog(@"model");
    }
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:[self getFilePathwith:self.videoNameSTR]];
    if (!blHave) {
        //没有
        return ;
    }else {
        //有则删除
        BOOL blDele= [[NSFileManager defaultManager] removeItemAtPath:[self getFilePathwith:self.videoNameSTR] error:nil];
        if (blDele) {
        }else {
        }
    }
}


#pragma mark -  -   - 设置发送消息时金豆的使用 -    -   -

- (void)setSendContentWithStyle:(IMAMsg *)text
{
    NSString *content = @"错误的文本消息！";
    
    //从消息簇中获取消息类型 消息状态等
    if (text.type == EIMAMSG_Text) {
        //文本消息
        NSMutableArray *elems = [NSMutableArray array];
        for (int index =0 ; index<text.msg.elemCount; index++ )
        {
            [elems addObject:[text.msg getElem:index]];
        }
        
        if (elems.count > 0) {
            TIMTextElem *timElem = elems[0];
            
            content = timElem.text;
            
            //扣费
            [self consumeRequestSourceWithContent:content];
        }
        
        
    }else if (text.type == EIMAMSG_Image){
        //图片消息
    }else if (text.type == EIMAMSG_Sound){
        content = @"语音消息";
        //扣费
        [self consumeRequestSourceWithContent:content];
        
    }else if (text.type == EIMAMSG_Custom){
        content = @"自定义消息";
        //扣费
        [self consumeRequestSourceWithContent:content];
    }
    
}

//消费金豆数目
- (void)consumeRequestSourceWithContent:(NSString *)sendContent
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        return;
    }
    //判断主播 / 用户
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
        return;
    }
    
    //编辑请求信息
    NSDictionary *dic = @{
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          @"anchorId":_receiver.userId,
                          @"content":sendContent
                          };
    
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/VideoChat/MessageCharge" parameters:dic resultClass:nil]subscribeNext:^(id x) {
        NSLog(@"金豆扣费成功");
        
    } error:^(NSError *error) {
        
        NSLog(@"金豆扣费不成功 %@",dic[@"ApiMessage"]);
        
    }];
    
    
}

- (void)recodeChatLoadwithType:(NSString *)type {
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",type, @"ctype",[[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"SendUserId",_receiver.userId,@"ReceiveUserId",nil];
    
    [BMHHTTPSession GET:@"MobileInterface/Chat/Chat.ashx" paraments:dic success:^(id  _Nullable JSON) {
        NSLog(@"ggggggggbbb == %@", JSON);
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    self.isFrst = NO;
}
- (void)showMsgs:(NSArray *)msgs
{
    if (self.isback) return;
    NSLog(@"msgsmsgsmsgsmsgs === %@", msgs);
    
    NSMutableArray *array = [NSMutableArray array];
    for (IMAMsg *msg in msgs)
    {
        NSInteger idx = [_messageList indexOfObject:msg];
        NSIndexPath *index = [NSIndexPath indexPathForRow:idx inSection:0];
        [array addObject:index];
    }
    
    [_tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationBottom];
    [_tableView endUpdates];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSIndexPath *index = [NSIndexPath indexPathForRow:_messageList.count - 1 inSection:0];
        NSLog(@"indexinmdex === %@", index);
        [_tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    });
}

- (void)modifySendInputStatus:(SendInputStatus)status
{
    _sendInputStatus = status;
}

- (void)onRestoreTitle:(NSTimer *)timer
{
    if (_inputStatusTimer)
    {
        [_inputStatusTimer invalidate];
        _inputStatusTimer = nil;
    }
    
    [self setChatTitle];
}

//发送文本
- (void)sendText:(NSString *)text
{
    if (text && text.length > 0)
    {
        IMAMsg *msg = [IMAMsg msgWithText:text];
        [self sendMsg:msg];
        
    }
}
- (void)didChangeToolBarHight:(CGFloat)toHeight
{
    __weak ChatViewController* weakself = self;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = weakself.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = weakself.view.frame.size.height - toHeight;
        weakself.tableView.frame = rect;
        [weakself.toolBar updateEmoj];
    }];
    
    if (_tableView.contentSize.height > _tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, _tableView.contentSize.height - _tableView.frame.size.height);
        [_tableView setContentOffset:offset animated:YES];
    }
}

#pragma mark - 发送语音
- (void)sendAudioRecord:(AudioRecord *)audio
{
    IMAMsg *msg = [IMAMsg msgWithSound:audio.audioData duration:audio.duration];
    [self judgeBalanceWithMsg:msg];
    
}

//===========================

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil)
    {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

#pragma mark - 发送图片
- (void)sendImage:(UIImage *)image orignal:(BOOL)orignal
{
    if (image)
    {
        //        IMAMsg *msg = [IMAMsg msgWithImage:image isOrignal:orignal];
        //        [self sendMsg:msg];
        //        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //        [HUD showAnimated:YES];
        SkyLabelWaitingView *lv = [SkyLabelWaitingView new];
        lv.ringColor = kNavigationColor;
        lv.ringWidth = 6.f;
        lv.label.font = [UIFont systemFontOfSize:16.f];
        lv.label.text = @"上传中";
        lv.r = 60;
        lv.rate = .8f;
        lv.label.textColor = kNavigationColor;
        lv.frame = CGRectMake(XQScreenW / 2 - 60, 150, 0, 0);
        [lv sizeToFit];
        [self.view addSubview:lv];
        [lv start];
        
        if(!self.imageSign)[self getUploadImageSign];
        //上传图片总共五步之   第四步: 初始化上传化上传任务
        _uploadPhotoTask = [[TXYPhotoUploadTask alloc] initWithImageData: UIImageJPEGRepresentation(image, 1.0)
                                                                fileName:@"name"
                                                                    sign:self.imageSign
                                                                  bucket:_imagebucket
                                                             expiredDate:0
                                                              msgContext:@"服务器透穿信息"
                                                                  fileId:nil];
        @weakify(self);
        //上传图片总共四步之    第五步: 上传
        [_uploadImageManager upload:_uploadPhotoTask
                           complete:^(TXYTaskRsp *resp, NSDictionary *context) {
                               @strongify(self);
                               [lv removeFromSuperview];
                               
                               _photoResp = (TXYPhotoUploadTaskRsp *)resp;
                               NSLog(@"上传图片的url%@ 上传图片的fileid = %@",_photoResp.photoURL,_photoResp.photoFileId);
                               NSLog(@"upload return=%d",_photoResp.retCode);
                               if ([_photoResp.photoURL isEqualToString:@"(null)"] || _photoResp.photoURL == nil || [_photoResp.photoURL isEqualToString:@""]) {
                                   [self getUploadImageSign];
                                   [HelpTool startTipViewWithText:@"上传失败,请重新上传" duration:1 type:kTipViewTypeNone];
                                   
                               }else {
                                   [self shangChuanImage:_photoResp.photoURL];
                                   
                               }
                               
                           }
                           progress:^(int64_t totalSize, int64_t sendSize, NSDictionary *context) {
                               //命中妙传，不走这里的！
                               NSLog(@" totalSize %lld",totalSize/1024/1024);
                               NSLog(@" sendSize %lld",sendSize);
                               NSLog(@" sendSize %@",context);
                               
                           }
                        stateChange:^(TXYUploadTaskState state, NSDictionary *context) {
                            switch (state) {
                                case TXYUploadTaskStateWait:
                                    NSLog(@"任务等待中");
                                    break;
                                case TXYUploadTaskStateConnecting:
                                    NSLog(@"任务连接中");
                                    break;
                                case TXYUploadTaskStateFail:
                                    [HelpTool startTipViewWithText:@"上传失败,请重新上传" duration:1 type:kTipViewTypeNone];
                                    [lv removeFromSuperview];
                                    
                                    NSLog(@"任务失败");
                                    break;
                                case TXYUploadTaskStateSuccess:
                                    NSLog(@"任务成功");
                                    
                                    break;
                                default:
                                    
                                    break;
                            }}];
        
    }
}
- (void)shangChuanImage:(NSString *)imageUrl {
    if (self.imageIndex == 4) {
        //付费图片  阅后即焚
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"rtype",@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",imageUrl,@"Path",[[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"Senduserid",_receiver.userId, @"Receiveuserid",@"0.5", @"payAmount", [[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"Userid",nil];
        
        [BMHHTTPSession GET:@"MobileInterface/User/RedImgVideo.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
            NSLog(@"注册之后的信息==-=-=-=-=-=-%@", JSON);
            if ([JSON[@"result"][@"errcode"] isEqualToString:@"804"]) {
                IMAMsg *msg = [IMAMsg msgWithCustom:self.imageIndex urlStr:imageUrl priceStr:@"5" imageStr:imageUrl withPayId:[NSString stringWithFormat:@"%@", JSON[@"result"][@"Id"]]];
                [self sendMsg:msg];
            }else {
                [HelpTool startTipViewWithText:@"上传失败,请重新上传" duration:1 type:kTipViewTypeNone];
            }
        } failure:^(NSError * _Nullable error) {
            
        }];
    }else {
        //免费图片  需要1金豆
        IMAMsg *msg = [IMAMsg msgWithCustom:self.imageIndex urlStr:imageUrl priceStr:@"0" imageStr:imageUrl withPayId:@""];
        [self judgeBalanceWithMsg:msg];
        
    }
}

#pragma mark - 判断账户余额 （在子类中实现方法）
-(void)judgeBalanceWithMsg:(IMAMsg *)msg
{
}

#pragma mark - 发送视频
- (void)sendVideo:(NSString *)urlPath withVideoImage:(UIImage *)videoImage withName:(NSString *)videoName {
    //    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    if(!self.imageSign)[self getUploadImageSign];
    //上传图片总共五步之   第四步: 初始化上传化上传任务
    _uploadPhotoTask = [[TXYPhotoUploadTask alloc] initWithImageData: UIImageJPEGRepresentation(videoImage, 1.0)
                                                            fileName:@"name"
                                                                sign:self.imageSign
                                                              bucket:_imagebucket
                                                         expiredDate:0
                                                          msgContext:@"服务器透穿信息"
                                                              fileId:nil];
    if ([urlPath.pathExtension isEqualToString:@"mp4"] == NO) {
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:urlPath]) {
            NSString *newPath = [[urlPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"mp4"];
            [[NSFileManager defaultManager] moveItemAtPath:urlPath toPath:newPath error:nil];
            urlPath = newPath;
        }
    }
    @weakify(self);
    //上传图片总共四步之    第五步: 上传
    [_uploadImageManager upload:_uploadPhotoTask
                       complete:^(TXYTaskRsp *resp, NSDictionary *context) {
                           @strongify(self);
                           //                           [HUD hideAnimated:YES];
                           
                           _photoResp = (TXYPhotoUploadTaskRsp *)resp;
                           NSLog(@"上传图片的url%@ 上传图片的fileid = %@",_photoResp.photoURL,_photoResp.photoFileId);
                           NSLog(@"upload return=%d",_photoResp.retCode);
                           if ([_photoResp.photoURL isEqualToString:@"(null)"] || _photoResp.photoURL == nil || [_photoResp.photoURL isEqualToString:@""]) {
                               [self getUploadImageSign];
                               [HelpTool startTipViewWithText:@"上传错误，请重新上传" duration:1 type:kTipViewTypeNone];
                               
                           }else {
                               //                               [self sendVideo:urlPath withImageStr:_photoResp.photoURL withVideoName:videoName];
                               NSString *uploadZipDirectory = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"uploadZip"];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:uploadZipDirectory] == NO) {
                                   [[NSFileManager defaultManager] createDirectoryAtPath:uploadZipDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                               }
                               [MBProgressHUD showMessage:@"" toView:self.view];
                               NSString *videoZIPName = [[videoName stringByDeletingPathExtension] stringByAppendingPathExtension:@"zip"];
                               dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                   if ([SSZipArchive createZipFileAtPath:[uploadZipDirectory stringByAppendingPathComponent:videoZIPName] withFilesAtPaths:@[urlPath]]) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [MBProgressHUD hideHUDForView:self.view animated:YES];
                                           [self sendVideo:[uploadZipDirectory stringByAppendingPathComponent:videoZIPName] withImageStr:_photoResp.photoURL withVideoName:videoName];
                                       });
                                   } else {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [MBProgressHUD showContent:@"视频处理失败，请重试" toView:self.view];
                                       });
                                   }
                               });
                           }
                           
                       }
                       progress:^(int64_t totalSize, int64_t sendSize, NSDictionary *context) {
                           //命中妙传，不走这里的！
                           NSLog(@" totalSize %lld",totalSize);
                           NSLog(@" sendSize %lld",sendSize);
                           NSLog(@" sendSize %@",context);
                           
                       }
                    stateChange:^(TXYUploadTaskState state, NSDictionary *context) {
                        switch (state) {
                            case TXYUploadTaskStateWait:
                                NSLog(@"任务等待中");
                                break;
                            case TXYUploadTaskStateConnecting:
                                NSLog(@"任务连接中");
                                break;
                            case TXYUploadTaskStateFail:
                                //                                [HUD hideAnimated:YES];
                                [HelpTool startTipViewWithText:@"上传错误，请重新上传" duration:1 type:kTipViewTypeNone];
                                
                                NSLog(@"任务失败");
                                break;
                            case TXYUploadTaskStateSuccess:
                                NSLog(@"任务成功");
                                //                                [HUD hideAnimated:YES];
                                
                                break;
                            default:
                                break;
                        }}];
    
    
}

#pragma mark - 发送视频
- (void)sendVideo:(NSString *)urlPath withImageStr:(NSString *)videoImage withVideoName:(NSString *)videoName {
    self.videoImageSTR = videoImage;
    SkyLabelWaitingView *lv = [SkyLabelWaitingView new];
    lv.ringColor = kNavigationColor;
    lv.ringWidth = 6.f;
    lv.label.font = [UIFont systemFontOfSize:16.f];
    lv.label.text = @"上传中";
    lv.r = 60;
    lv.rate = .8f;
    lv.label.textColor = kNavigationColor;
    lv.frame = CGRectMake(XQScreenW / 2 - 60, 150, 0, 0);
    [lv sizeToFit];
    [self.view addSubview:lv];
    [lv start];
    if(!self.videoSign)[self getUploadVidepSign];
    //    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    HUD.label.text = LoadingUpload;
    //[HUD showAnimated:YES];
    NSString *videoZIPName = [[videoName stringByDeletingPathExtension] stringByAppendingPathExtension:@"zip"];
    TXYVideoFileInfo *videoFileInfo = [[TXYVideoFileInfo alloc]init];
    videoFileInfo.title = videoName;
    videoFileInfo.desc = @"videodesc1";
    videoFileInfo.isCheck = 0;
    videoFileInfo.coverUrl= videoImage;//视频的自定义封面
    
    //上传视频总共四步之    第四步: 初始化上传化上传任务
    NSString *dir = [NSString stringWithFormat:@"/"];//[NSString stringWithFormat:@"/12",bucket];
    //    _uploadVideoTask = [[TXYVideoUploadTask alloc] initWithPath:urlPath
    //                                                           sign:_videoSign
    //                                                         bucket:_bucket
    //                                                       fileName:videoName
    //                                                customAttribute:@"customAttribute"
    //                                                uploadDirectory:dir
    //                                                  videoFileInfo:videoFileInfo
    //                                                     msgContext:@"msgContext"
    //                                                     insertOnly:NO];
    
    _uploadVideoTask = [[TXYFileUploadTask alloc] initWithPath:urlPath
                                                          sign:_videoSign
                                                        bucket:_bucket
                                                      fileName:videoZIPName
                                               customAttribute:@"customAttribute"
                                               uploadDirectory:dir
                                                    insertOnly:NO];
    //上传视频总共五步之   第五步: 上传任务
    DECLARE_WEAK_SELF;
    @weakify(self);
    BOOL isSuccess = [_uploadVideoManager upload:_uploadVideoTask
                                        complete:^(TXYTaskRsp *resp, NSDictionary *context) {
                                            DECLARE_STRONG_SELF;
                                            @strongify(self);
                                            if (!strongSelf) return;
                                            _videoResp = (TXYVideoUploadTaskRsp *)resp;
                                            NSLog(@"上传视频的url%@ 上传视频的fileid = %@",_videoResp.fileURL,_videoResp.fileId);
                                            NSLog(@"video is source url%@",_videoResp.sourceURL);
                                            //                           NSString *filePath = [self getDirectoryOfDocumentFileWithName:videoName];
                                            //                           NSLog(@"vbbbbbbbbb == %@", filePath);
                                            //                           if (filePath) {
                                            //                               [self removeFileAtPath:filePath];
                                            //                           }
                                            [self removeFileAtPath:urlPath];
                                            [lv removeFromSuperview];
                                            if (resp.retCode < 0 && resp.retCode != -177) {
                                                [self getUploadVidepSign];
                                                [HelpTool startTipViewWithText:resp.descMsg duration:1 type:kTipViewTypeNone];
                                            }else {
                                                
                                                [self sendrDateFirstWithImageStr:videoImage withVideoName:videoZIPName];
                                                
                                            }
                                            //
                                        }
                                        progress:^(int64_t totalSize, int64_t sendSize, NSDictionary *context) {
                                            //命中妙传，不走这里的！
                                            NSLog(@" totalSize %lld",totalSize);
                                            NSLog(@" sendSize %lld",sendSize);
                                            NSLog(@" sendSize %@",context);
                                            CGFloat precent = 1.0 * sendSize / totalSize;
                                            lv.label.text = [NSString stringWithFormat:@"上传%.0f％",precent * 100];
                                        }
                                     stateChange:^(TXYUploadTaskState state, NSDictionary *context) {
                                         switch (state) {
                                             case TXYUploadTaskStateWait:
                                                 NSLog(@"demoapp log 任务等待中");
                                                 break;
                                             case TXYUploadTaskStateConnecting:
                                                 NSLog(@"demoapp log 任务连接中");
                                                 break;
                                             case TXYUploadTaskStateFail:
                                                 NSLog(@"demoapp log 任务失败");
                                                 NSLog(@"jjjjj === %@  %ld", context, (long)state);
                                                 //                                [HUD hideAnimated:YES];
                                                 [lv removeFromSuperview];
                                                 
                                                 //                                [HelpTool startTipViewWithText:@"上传错误，请重新上传" duration:1 type:kTipViewTypeNone];
                                                 
                                                 break;
                                             case TXYUploadTaskStateSuccess:
                                                 NSLog(@"demoapp log 任务成功");
                                                 break;
                                             default:
                                                 break;
                                         }}];
    NSLog(@"6276");
}

#pragma mark - 上传成功后转换成IMAMsg消息体然后发送消息
- (void)sendrDateFirstWithImageStr:(NSString *)imageStr withVideoName:(NSString *)videoNameStr {
    
    NSLog(@"我上传成功了啊");
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    //时间戳
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"rtype",@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",videoNameStr,@"Path",[[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"Senduserid",_receiver.userId, @"Receiveuserid",[NSString stringWithFormat:@"%ld", self.currentMoney], @"payAmount", [[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"Userid",nil];
    
    [BMHHTTPSession GET:@"MobileInterface/User/RedImgVideo.ashx" paraments:dicRegister success:^(id  _Nullable JSON) {
        NSLog(@"注册视频后的信息==-=-=-=-=-=-%@", JSON);
        if ([JSON[@"result"][@"errcode"] isEqualToString:@"804"]) {
            IMAMsg *msgs = [IMAMsg msgWithCustom:2 urlStr:videoNameStr priceStr:[NSString stringWithFormat:@"%ld", self.sendMoney] imageStr:imageStr withPayId:[NSString stringWithFormat:@"%@", JSON[@"result"][@"Id"]]];
            
            [self judgeBalanceWithMsg:msgs];
            
        }else {
            [HelpTool startTipViewWithText:@"上传失败,请重新上传" duration:1 type:kTipViewTypeNone];
        }
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    
}


#pragma mark -- 拍摄照片或者拍摄视频完成代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
    {
        UIImage *image = [info[UIImagePickerControllerOriginalImage] fixOrientation];
        NSData *data = UIImagePNGRepresentation(image);
        NSInteger fileSize = data.length / 1024/ 1024;
        NSLog(@"fileSize == %ld",fileSize);
        CGSize imagesize = image.size;
        
        if(data.length > 20 * 1024 * 1024)
        {
            imagesize.height = image.size.height / 8;
            imagesize.width = image.size.width / 8;
            
        }else if (data.length > 10 * 1024 * 1024 && data.length <= 20 * 1024 * 1024){
            imagesize.height = image.size.height / 6;
            imagesize.width = image.size.width / 6;
            
        }else if (data.length > 4 * 1024 * 1024 && data.length <= 10 * 1024 * 1024){
            imagesize.height = image.size.height / 5;
            imagesize.width = image.size.width / 5;
            
        }
        else if (data.length <  1024 * 1024 / 2){
            imagesize.height = image.size.height;
            imagesize.width = image.size.width;
            
        }else {
            imagesize.height = image.size.height / 3;
            imagesize.width = image.size.width / 3;
            
        }
        
        //对图片大小进行压缩--
        
        image = [self imageWithImage:image scaledToSize:imagesize];
        
        [self sendImage:image orignal:0];
        
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    else if([mediaType isEqualToString:(NSString*)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
        //        if (self.imagePicker.mediaTypes.count == 2)
        //        {
        NSURL *url = info[UIImagePickerControllerMediaURL];
        NSLog(@"vvvvv == %@", info);
        
        NSArray *arr = [url.absoluteString componentsSeparatedByString:@"/"];
        NSString * fileName = [arr lastObject];
        
        NSString *token = [[HelpTool getIOSuuid] substringToIndex:3];
        self.videoNameSTR = [NSString stringWithFormat:@"%@_%@", token, fileName];
        NSArray *array = [self.videoNameSTR componentsSeparatedByString:@"."]; //从字符A中分隔成2个元素的数组
        self.videoNameSTR = [NSString stringWithFormat:@"%@%@",array[0],@".mp4"];
        
//        NSError *err = nil;
//        NSData* data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&err];
//        if(data.length < 28 * 1024 * 1024)
//        {
//            //                [self sendImage:thumbnail orignal:0];
//
//            //文件最大不超过28MB
//        }
//        else
//        {
//            [[HUDHelper sharedInstance] tipMessage:@"发送的文件过大"];
//        }
        AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
        NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
        /**
         AVAssetExportPresetMediumQuality 表示视频的转换质量，
         */
        if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
            AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
            
            //转换完成保存的文件路径
            NSString * resultPath = [self getFilePathwith:self.videoNameSTR];
            
            exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
            //要转换的格式，这里使用 MP4
            exportSession.outputFileType = AVFileTypeMPEG4;
            //转换的数据是否对网络使用优化
            exportSession.shouldOptimizeForNetworkUse = YES;
            //异步处理开始转换
            [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
             {
                 //转换状态监控
                 switch (exportSession.status) {
                     case AVAssetExportSessionStatusUnknown:
                         NSLog(@"AVAssetExportSessionStatusUnknown");
                         break;
                         
                     case AVAssetExportSessionStatusWaiting:
                         NSLog(@"AVAssetExportSessionStatusWaiting");
                         break;
                         
                     case AVAssetExportSessionStatusExporting:
                         NSLog(@"AVAssetExportSessionStatusExporting");
                         break;
                     case AVAssetExportSessionStatusFailed:
                         NSLog(@"AVAssetExportSessionStatusFailed");
                         break;
                     case AVAssetExportSessionStatusCancelled:
                         NSLog(@"AVAssetExportSessionStatusCancelled");
                         break;
                         
                     case AVAssetExportSessionStatusCompleted:
                     {
                         //转换完成
                         NSLog(@"AVAssetExportSessionStatusCompleted");
                         self.videoURL = [self getFilePathwith:self.videoNameSTR];
                         NSParameterAssert(avAsset);
                         AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:avAsset];
                         assetImageGenerator.appliesPreferredTrackTransform = YES;
                         assetImageGenerator.apertureMode =AVAssetImageGeneratorApertureModeEncodedPixels;
                         CGImageRef thumbnailImageRef = NULL;
                         CFTimeInterval thumbnailImageTime = 0;
                         NSError *thumbnailImageGenerationError = nil;
                         thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
                         if(!thumbnailImageRef){
                             NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
                         }
                         UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef] : nil;
                         self.videoImage = thumbnailImage;
                         [self addVideoMoneyViewWitImage:thumbnailImage];
                         break;
                     }
                 }
                 
             }];
            
        }

    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    _imagePicker = nil;
}

#pragma mark - moreView
-(void)hiddenKeyBoard
{
    [_toolbar endEditing:YES];
    
}

#pragma mark - MyMoreViewDelegate
- (void)moreViewMoneyImageAction
{
    self.isenter = NO;
//    [HelpTool statStartEventId:@"10802" eventLabel:@"私聊界面点红包照片"];
    // 隐藏键盘
    [self hiddenKeyBoard];
    //    //收费照片
    //    // 弹出照片选择
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    self.navigationItem.rightBarButtonItem.tintColor = kBlackColor;
    [[UINavigationBar appearance]setTintColor:kBlackColor];
    self.navigationItem.leftBarButtonItem.tintColor = kBlackColor;
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    self.imageIndex = 4;
    
}
- (void)moreViewMoneyVideoAction {
    self.isenter = NO;
    [HelpTool statStartEventId:@"10803" eventLabel:@"私聊界面点红包视频"];
    [self hiddenKeyBoard];
    
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    self.imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    self.imagePicker.cameraCaptureMode =UIImagePickerControllerCameraCaptureModePhoto;
    self.imagePicker.cameraDevice =UIImagePickerControllerCameraDeviceRear;
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    self.imageIndex = 1;
    
    //老代码
//    //收费视频
//    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc]init];
//
//    picker.maximumNumberOfSelection = 1;
//    picker.assetsFilter = [ALAssetsFilter allVideos];
//    picker.showEmptyGroups = NO;
//    picker.wetherPhoto = NO;
//    picker.delegate = self;
//    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,NSDictionary *bindings){
//        if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType]isEqual:ALAssetTypePhoto]) {
//            NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration]doubleValue];
//            return duration >= 5;
//        }else{
//            return  YES;
//        }
//    }];
//
//    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark -- 发送图片 跳转选择图片界面
- (void)moreViewFreeImageAction
{
    self.isenter = NO;
    [HelpTool statStartEventId:@"10804" eventLabel:@"私聊界面点免费照片"];
    [self hiddenKeyBoard];
    // 弹出照片选择
    HXPhotoManager * manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
    manager.configuration.clarityScale = 1.7;
    manager.configuration.hideOriginalBtn = YES;
    manager.configuration.filtrationICloudAsset = YES;
    manager.configuration.maxNum = 9;
    manager.configuration.photoMaxNum = 9;
    manager.configuration.videoMaxNum = 9;
    manager.configuration.rowCount = 3;
    manager.configuration.videoMaxDuration = 60;
    manager.configuration.saveSystemAblum = YES;
    manager.configuration.showDateSectionHeader = NO;
    manager.configuration.reverseDate = YES;
    manager.configuration.replaceCameraViewController = NO;
    manager.configuration.openCamera = NO;
    manager.configuration.videoCanEdit = NO;
    manager.configuration.photoCanEdit = NO;
    manager.configuration.lookLivePhoto = YES;
    manager.configuration.requestImageAfterFinishingSelection = YES;
    manager.configuration.selectTogether = YES;
    manager.configuration.themeColor = KButtonTextColor;
    [self hx_presentAlbumListViewControllerWithManager:manager delegate:self];
}

- (void)albumListViewController:(HXAlbumListViewController *)albumListViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original {
    if(allList.count > 0)
    {
        HXPhotoModel * model = allList[0];
        [self getResourcesToUploading:model.asset AndImage:model.thumbPhoto];
        for(int i = 1; i < allList.count; i++)
        {
            [self.mediaArray addObject:allList[i]];
        }
    }
}

#pragma mark -- 选中的图片或视频资源对象 获取对象地址并上传发送
-(void)getResourcesToUploading:(PHAsset *)phAsset AndImage:(UIImage *)image
{
    if (phAsset.mediaType == PHAssetMediaTypeVideo) {
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            NSURL *url = urlAsset.URL;
            NSArray *arr = [url.absoluteString componentsSeparatedByString:@"/"];
            NSString * fileName = [arr lastObject];
            
            NSString *token = [[HelpTool getIOSuuid] substringToIndex:3];
            self.videoNameSTR = [NSString stringWithFormat:@"%@_%@", token, fileName];
            NSArray *array = [self.videoNameSTR componentsSeparatedByString:@"."]; //从字符A中分隔成2个元素的数组
            self.videoNameSTR = [NSString stringWithFormat:@"%@%@",array[0],@".mp4"];
            //将mov转换成mp4格式
            NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:urlAsset];
            if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
                AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:urlAsset presetName:AVAssetExportPresetMediumQuality];
                exportSession.outputURL = [NSURL fileURLWithPath:[self getFilePathwith:self.videoNameSTR]];
                NSLog(@"resultPath = %@",[self getFilePathwith:self.videoNameSTR]);
                exportSession.outputFileType = AVFileTypeMPEG4;
                exportSession.shouldOptimizeForNetworkUse = YES;
                [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
                 {
                     switch (exportSession.status) {
                         case AVAssetExportSessionStatusUnknown:
                             NSLog(@"AVAssetExportSessionStatusUnknown");
                             break;
                         case AVAssetExportSessionStatusWaiting:
                             NSLog(@"AVAssetExportSessionStatusWaiting");
                             break;
                         case AVAssetExportSessionStatusExporting:
                             NSLog(@"AVAssetExportSessionStatusExporting");
                             break;
                         case AVAssetExportSessionStatusCompleted:
                             NSLog(@"AVAssetExportSessionStatusCompleted");
                             self.videoURL = [self getFilePathwith:self.videoNameSTR];
                             self.videoImage = image;
                             [self addVideoMoneyViewWitImage:image];
                             break;
                         case AVAssetExportSessionStatusFailed:
                             NSLog(@"AVAssetExportSessionStatusFailed");
                             break;
                     }
                 }];
            }
            //
//            NSMutableData *mmdat = [NSMutableData dataWithContentsOfURL:url];
//            [mmdat writeToFile:[self getFilePathwith:self.videoNameSTR] atomically:YES];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//            [data writeToFile:[self getFilePathwith:self.videoNameSTR] atomically:YES];

        }];
    }else
    {
        self.imageIndex = 1;
        [[PHImageManager defaultManager] requestImageDataForAsset:phAsset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            UIImage* upLoadImage = [UIImage imageWithData:imageData];
            if (orientation != UIImageOrientationUp) {
                // 图片弯曲  回正
                upLoadImage = [upLoadImage fixOrientation];
            }
            NSData *data = UIImagePNGRepresentation(upLoadImage);
            NSInteger fileSize = data.length / 1024/ 1024;
            NSLog(@"fileSize == %ld",fileSize);
            CGSize imagesize = upLoadImage.size;
            
            if(data.length > 20 * 1024 * 1024)
            {
                imagesize.height = upLoadImage.size.height / 8;
                imagesize.width = upLoadImage.size.width / 8;
                
            }else if (data.length > 10 * 1024 * 1024 && data.length <= 20 * 1024 * 1024){
                imagesize.height = upLoadImage.size.height / 6;
                imagesize.width = upLoadImage.size.width / 6;
                
            }else if (data.length > 4 * 1024 * 1024 && data.length <= 10 * 1024 * 1024){
                imagesize.height = upLoadImage.size.height / 5;
                imagesize.width = upLoadImage.size.width / 5;
                
            }
            else if (data.length <  1024 * 1024 / 2){
                imagesize.height = upLoadImage.size.height;
                imagesize.width = upLoadImage.size.width;
                
            }else {
                imagesize.height = upLoadImage.size.height / 3;
                imagesize.width = upLoadImage.size.width / 3;
                
            }
            
            //对图片大小进行压缩--
            
            upLoadImage = [self imageWithImage:upLoadImage scaledToSize:imagesize];
            
            [self sendImage:upLoadImage orignal:0];
        }];
    }
}

#pragma mark --老版发送视频的方法
//-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
//    [self dismissViewControllerAnimated:YES completion:^{
//        NSDate *date= [assets[0] valueForProperty:ALAssetPropertyDate];
//        UIImage *image = [UIImage imageWithCGImage:[assets[0] thumbnail]];
//        NSString *fileName = [[assets[0] defaultRepresentation] filename];
//        NSURL *url = [[assets[0] defaultRepresentation] url];
//        NSInteger fileSize = [[assets[0] defaultRepresentation] size] / 1024;
//
//        NSLog(@"date = %@",date);
//        NSLog(@"fileName = %@",fileName);
//        NSLog(@"url = %@",url);
//        NSLog(@"fileSize = %ld",fileSize);
//        NSString *token = [[HelpTool getIOSuuid] substringToIndex:3];
//
//        self.videoNameSTR = [NSString stringWithFormat:@"%@_%@", token, fileName];
//
//        NSMutableData *mmdat = [NSMutableData dataWithContentsOfURL:url];
//        [mmdat writeToFile:[self getFilePathwith:self.videoNameSTR] atomically:YES];
//
//        ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
//        [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) // substitute YOURURL with your url of video
//         {
//             ALAssetRepresentation *rep = [asset defaultRepresentation];
//             Byte *buffer = (Byte*)malloc(rep.size);
//             NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
//             NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
//             [data writeToFile:[self getFilePathwith:self.videoNameSTR] atomically:YES]; //you can remove this if only nsdata needed
//         }
//                     failureBlock:^(NSError *err) {
//                         NSLog(@"Error: %@",[err localizedDescription]);
//                     }];
//
//        NSString  *videoPath = [self getFilePathwith:self.videoNameSTR];
//        NSLog(@"parhhh == %@", videoPath);
//        self.videoURL = videoPath;
//        self.videoImage = image;
//
//        [self addVideoMoneyViewWitImage:image];
//
//    }];
//}

- (void)addVideoMoneyViewWitImage:(UIImage *)videoImage {
    NSInteger index = 10;
    self.sendMoney = 10;
    self.currentMoney = self.sendMoney / index;
    [self sendVideo:self.videoURL withVideoImage:self.videoImage withName:self.videoNameSTR];
}
#pragma mark //点击moneyVideo的代理
-(void)videoCurrentMoneyCount:(NSInteger)cuttentMoney {
    //    [self.moneyView removeFromSuperview];
    //    NSInteger index = 10;//[[[NSUserDefaults standardUserDefaults] objectForKey:@""] integerValue];
    //    self.sendMoney = cuttentMoney;
    //    self.currentMoney = cuttentMoney / index;
    //    [self sendVideo:self.videoURL withVideoImage:self.videoImage withName:self.videoNameSTR];
}
//获取文件路径
- (NSString *)getFilePathwith:(NSString *)videoStr {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,  NSUserDomainMask , YES) firstObject];
    NSString *filePath = [path stringByAppendingPathComponent:videoStr];
    return filePath;
}


- (NSString *)getDirectoryOfDocumentFileWithName:(NSString *)fileName {
    NSString *documentsPath = [self getDirectoryOfDocumentFolder];
    if (documentsPath) {
        return [documentsPath stringByAppendingPathComponent:fileName]; // 获取用于存取的目标文件的完整路径
    }
    
    return nil;
}


- (NSString *)getDirectoryOfDocumentFolder {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); // 获取所有Document文件夹路径
    NSString *documentsPath = paths[0]; // 搜索目标文件所在Document文件夹的路径，通常为第一个
    
    if (!documentsPath) {
        NSLog(@"Documents目录不存在");
    }
    
    return documentsPath;
}
- (void)removeFileAtPath:(NSString *)filePath {
    NSError *error = nil;
    if ([self isFileExitsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        
        if (error) {
            NSLog(@"移除文件失败，错误信息：%@", error);
        }
        else {
            NSLog(@"成功移除文件");
        }
    }
    else {
        NSLog(@"文件不存在");
    }
}
- (BOOL)isFileExitsAtPath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
        return YES;
    }
    
    return NO;
}

- (void)requestData {
    NSString * useridStr   = [_receiver userId];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        NSLog(@"=====dd个人资料json====%@",JSON);
        [self getBeautyDic:JSON[@"result"][@"data"]];
    } failure:^(NSError * _Nullable error) {
        
    }];
    
}
- (void)getBeautyDic:(NSDictionary *)beautDic {
    
    self.userInfoModel = [[HomeCallModel alloc] initWithDict:beautDic];
    //    [self.tableView reloadData];
}

#pragma mark - 私聊界面点视频聊天
//视频通话1V1
- (void)moreVideChatVideoAction
{
    [self analyticsEvent4];
    [self requestDataVideChat];
}

- (void)clickInviteVideoChatCell {
    
    [self requestDataVideChat];
}

-(void)requestDataVideChat
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * useridStr   = [_receiver userId];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        NSLog(@"=====dd个人资料json====%@",JSON);
        NSString  *status  =  JSON[@"result"][@"errcode"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([F(@"%@", status) isEqualToString:@"803"]) {
            [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            
            [self sendMsg:msg];
        }else{
            [self getBeautyDic:JSON[@"result"][@"data"]];
            
        }
        
    } failure:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
    
    if ([self checkCameraAuthorization])
    {
        [self videoChatPrivate];
    }
}

-(void)videoChatPrivate
{
    [HelpTool statStartEventId:@"10806" eventLabel:@"私聊界面点视频聊天"];
    // 隐藏键盘，只能选择图片或视频文件
    [self hiddenKeyBoard];
    [self makeVideoChatIsFree:NO];
}

- (void)getfreeVideoChatCountSuccess:(void (^)(void))success fail:(void (^)(void))fail {
    NSDictionary *parameters = @{
                                 @"type" : @"18",
                                 @"userId" : [[NSUserDefaults standardUserDefaults] objectForKey:UserID]
                                 };
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:parameters success:^(id  _Nullable JSON) {
        if ([JSON[@"result"][@"errcode"] integerValue] == 0) {
            NSInteger freeCount = [JSON[@"result"][@"data"] integerValue];
            if (freeCount > 0) {
                if (success) {
                    success();
                }
            } else {
                if (fail) {
                    fail();
                }
            }
        } else {
            if (fail) {
                fail();
            }
        }
        
    } failure:^(NSError * _Nullable error) {
        if (fail) {
            fail();
        }
    }];
}

- (void)makeVideoChatIsFree:(BOOL)isFree {//v2版本
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:[_receiver userId] userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        HomeCallModel *model = x;
        NSString * callID =  model.CallId;
        CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
        make.IsOneTimeCall = model.IsOneTimeCall;
        make.UserFreeSecond = model.UserCardSecond;
        make.peerId = [NSString stringWithFormat:@"%@",model.AnchorId];
        make.headStr = _receiver.icon;
        make.nickNameStr = _receiver.nickName;
        make.ismic = YES;
        make.iscinema = YES;
        make.callid = callID;
        make.videoid = [NSString stringWithFormat:@"%@",callID];
        make.moneyStr =@"20";
        make.gradeStr = [NSString stringWithFormat:@"%@",self.userInfoModel.BGradeIcon];
        
        [self presentViewController:make animated:YES completion:nil];
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        if (error.code == 6) {  //余额不足
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
            TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
            topVC.In_purchase = isIn_purchase;
            [self.navigationController pushViewController:topVC animated:YES];
        } else {  //被拉入黑名单//对方已屏蔽视聊
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }
    }];
}

#pragma mark - 私聊界面顶部点视频聊天

-(void)moreVideChatVideoNavAction
{
    
    [self requestDataVideChatNav];
}

-(void)requestDataVideChatNav
{
    NSString * useridStr   = [_receiver userId];
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        
        NSLog(@"=====dd个人资料json====%@",JSON);
        NSString  *status  =  JSON[@"result"][@"errcode"];
        
        if ([F(@"%@", status) isEqualToString:@"803"]) {
            
            
            [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
            IMAMsg *msg = [IMAMsg msgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            
            [self sendMsg:msg];
            
        }else{
            
            
            [self getBeautyDic:JSON[@"result"][@"data"]];
            
            if ([self checkCameraAuthorization])
            {
                [self videoChatPritaveNav];
            }
            
        }
        
    } failure:^(NSError * _Nullable error) {
        
    }];
}

-(void)videoChatPritaveNav
{
    [HelpTool statStartEventId:@"10807" eventLabel:@"私聊界面顶部点视频聊天"];
    // 隐藏键盘，只能选择图片或视频文件
    [self hiddenKeyBoard];
    
    
    
    self.isenter = YES;
    
    
    
    if (self.userInfoModel.ChatStatus == 2 || self.userInfoModel.ChatStatus == 0)  {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
        NSString *peeridStr = [_receiver userId];
        
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        //令牌
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        
        NSString *sTimeUser = [fmt stringFromDate:now];
        NSString *objIDUser = @"0";
        NSString *publicKeyUser = @"BMH2014YDYWB";
        NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
        natUser = [natUser md5Encrypt];
        
        
        NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"Type",uid,@"Userid",peeridStr,@"Anchorid", @"2",@"Rtype",locationString,@"Timestamp",natUser,@"Appsign",nil];
        [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
            NSString * errcode  = JSON[@"result"][@"errcode"];
            NSString * videoID =  JSON[@"result"][@"data"][@"Id"];
            NSLog(@"通话发通话发 == %@",JSON);
            
            if ([errcode isEqualToString:@"0"])
            {
                NSString * callID =  [NSString stringWithFormat:@"%@",JSON[@"result"][@"data"][@"CallID"]];
                
                //                NSUser_save(videoID,kVideoID);//创建通话ID
                //                NSUser_save(callID,ChatToChatCallId);//创建通话ID
                //
                //                //[HelpTool startTipViewWithText:@"通话发起成功!" duration:2.0f type:kTipViewTypeNone];
                //                CallMakeViewController *make = [[CallMakeViewController alloc] init];
                //                make.peerId = [NSString stringWithFormat:@"%@",self.userInfoModel.userID];
                //                make.headStr = self.userInfoModel.HeadImg;
                //                make.nickNameStr = self.userInfoModel.NickName;
                //                make.detailStr = [NSString stringWithFormat:@"%@ %@",self.userInfoModel.HostCity,self.userInfoModel.job];
                //                make.addressStr = self.userInfoModel.HostCity;
                //                make.ageStr = self.userInfoModel.Age;
                //                make.jobStr = self.userInfoModel.job;
                //                make.ismic = YES;
                //                make.iscinema = YES;
                //                make.callid =callID;
                //                make.videoid = [NSString stringWithFormat:@"%@",videoID];
                //
                //                make.moneyStr =@"20" ;
                //                make.gradeStr = [NSString stringWithFormat:@"%@",self.userInfoModel.BGradeIcon];
                //                NSLog(@"vvvvvvvbbbbbbnn == %@  -- %@", make.headStr, make.nickNameStr);
                //                [self presentViewController:make animated:YES completion:nil];
                
            }else if ([errcode isEqualToString:@"-2"])
            {
                [HelpTool startTipViewWithText:@"你的账号余额不足，请充值！" duration:2.0f type:kTipViewTypeNone];
                
            }else if ([errcode isEqualToString:@"-10"])
            {
                [HelpTool startTipViewWithText:@"您的通话发起失败,请重新发起!" duration:2.0f type:kTipViewTypeNone];
                
            }else if ([errcode isEqualToString:@"-3"])
            {
                [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
                IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
                
                [self sendMsg:msg];
                
            }else if ([errcode isEqualToString:@"-4"])
            {
                [HelpTool startTipViewWithText:@"已成为黑名单用户！" duration:2.0f type:kTipViewTypeNone];
                
            }
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"===创建通话====%@",JSON);
        } failure:^(NSError * _Nullable error) {
            NSLog(@"===创建通话失败===%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
        }];
    }
    else {
        [HelpTool startTipViewWithText:@"对方正忙!" duration:2.0f type:kTipViewTypeNone];
        
    }
}

#pragma mark -

-(void)privateInfo
{
    
    NSDictionary * privateDic = [NSDictionary dictionaryWithObjectsAndKeys:@"2",@"Type",[_receiver userId],@"Userid", nil];
    [BMHHTTPSession GET:@"/MobileInterface/User/UserChatSettings.ashx" paraments:privateDic success:^(id  _Nullable JSON) {
        NSLog(@"===获取私聊信息===%@",JSON);
        
        self.voiceSwitchValue = JSON[@"result"][@"data"][@"IsReceiveLanguageChat"];//是否语音
        self.VideoSwitchValue = JSON[@"result"][@"data"][@"IsLiveLanguageChat"];   //是否视频
        self.isForVoicePrice  = JSON[@"result"][@"data"][@"LanguageChatPrice"];    //语音聊天价格
        self.isForVideoPrice  = JSON[@"result"][@"data"][@"LiveChatPrice"];        //视频聊天价格
        self.chatStatus = [JSON[@"result"][@"data"][@"LiveChatPrice"] intValue];
        //        [self.tableView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
}


#pragma mark -- 电话聊天实现方法
- (void)moreVideChatVoiceAction
{
    // 隐藏键盘
    [self hiddenKeyBoard];
    //检查是否可以通话
    [self setUserInfoAction];
    
    HomeCallModel *model = nil;
    if ([self checkCameraAuthorization]) {
        [self VoiceChatWithModel:model];
    }
    
}

//设置令牌信息
- (void)setUserInfoAction
{
    [self analyticsEvent4];
    NSString * useridStr = [_receiver userId];
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
}


#pragma mark ***************发起语音
- (void)VoiceChatWithModel:(HomeCallModel *)model2 {//v2版本
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/VideoChat/Connect1V1VoiceChat" parameters:@{
                                                                                                         @"userId":[[XLAccountManager shareInstance] model].Id,
                                                                                                         @"anchorId":K_DEFULT([_receiver userId]),
                                                                                                         @"type":@"1"
                                                                                                         } resultClass:[HomeCallModel class]] subscribeNext:^(id x) {
        
        [MBProgressHUD hideHUDForView:self.view];
        HomeCallModel *model = x;
        XLMakeVoiceChatVC *make = [[XLMakeVoiceChatVC alloc] init];//拔打电话
        //        make.IsOneTimeCall = model.IsOneTimeCall;
        //        make.UserFreeSecond = model.UserFreeSecond;
        make.peerId = [NSString stringWithFormat:@"%@",model.AnchorId];
        make.headStr = _receiver.icon;
        make.nickNameStr = _receiver.nickName;
        make.detailStr = [NSString stringWithFormat:@"%@ %@",model.HostCity,model.job];
        make.addressStr = model.HostCity;
        make.ageStr = model.Age;
        make.jobStr = model.job;
        make.ismic = YES;
        //        make.iscinema = YES;
        make.callid = model.CallId;
        make.videoid = model.CallId;
        make.moneyStr = @"20";
        make.gradeStr = [NSString stringWithFormat:@"%@",model.BGradeIcon];
        UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:make];
        [self presentViewController:nav animated:YES completion:nil];
        
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (error.code == 6) {  //余额不足
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
            TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
            topVC.In_purchase = isIn_purchase;
            [self.navigationController pushViewController:topVC animated:YES];
        } else {  //被拉入黑名单//对方已屏蔽视聊
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }
    }];
}



- (void)moreVideFlowerAction {
    [self analyticsEvent5];
    [HelpTool statStartEventId:@"10801" eventLabel:@"私聊界面点礼物"];
    [self hiddenKeyBoard];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.keyboardView = [[KeyboardView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height) array:self.senderGiftArr WithColor:RGBA_HEX(0x0C0D10, 0.95) withIslive:NO];
    self.keyboardView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.3];
    
    self.keyboardView.mydelegate = self;
    
    [window addSubview:self.keyboardView];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [self.keyboardView addGestureRecognizer:tapGesture];
    
}
#pragma mark ***********充值
- (void)keyboardViewChargeBtn{
    [self.keyboardView removeFromSuperview];
    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
    topVC.In_purchase = NO;
    topVC.backActionBlock = ^() {
        [self dismissViewControllerAnimated:YES completion:NULL];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topVC];
    
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark ***********赠送礼物
- (void)keyboardViewDidSendUrl:(NSString *)imageUrl moverImageUrl:(NSString *)moverUrl name:(NSString *)name price:(float)price giftID:(NSInteger)giftID {
    if (_giftAnimalFinish == YES) {
        _giftAnimalFinish = NO;
        
        NSLog(@"vvvvvvvv == %@ --- %@", imageUrl, [[NSUserDefaults standardUserDefaults] objectForKey:UserID]);
        
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@",objID,[[NSUserDefaults standardUserDefaults] objectForKey:UserID], publicKey, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        NSDictionary *  dicRegister= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"type",locationString,@"Timestamp",nat,@"Appsign",[NSString stringWithFormat:@"%ld", giftID],@"giftId",[[NSUserDefaults standardUserDefaults] objectForKey:UserID], @"giveUserId",[_receiver userId], @"giftsUserId", [NSString stringWithFormat:@"%f", price], @"giftPrice", @"1", @"giftNumber",@"",@"Intro",@"",@"DynamicID", nil];
        
        [[[XLHTTPSessionManager sharedManager]XLV2POST:@"/Api/v2/Gift/GiveGift" parameters:dicRegister resultClass:nil] subscribeNext:^(id x) {
            NSLog(@"礼物僧送==-=-=-=-=-=-%@", x);
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [MBProgressHUD showContent:@"赠送成功" toView:window];
            if (x) {
                //            IMAMsg *msgs = [IMAMsg msgWithCustom:3 priceStr:[NSString stringWithFormat:@"%0.f", price * 10] giftBubbleImageUrl:moverUrl giftMsgImageUrl:imageUrl NameStr:name];
                //            [self sendMsg:msgs];
                [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
                
            }
        } error:^(NSError *error) {
            _giftAnimalFinish = YES;
            if (error.code == -1) {
                [self.keyboardView removeFromSuperview];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的余额不足,是否前往充值?" preferredStyle: UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //点击按钮的响应事件；
                    
                    
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                    topVC.In_purchase = isIn_purchase;
                    [self.navigationController pushViewController:topVC animated:YES];
                    
                }]];
                [self.navigationController presentViewController:alert animated:YES completion:nil];
            }else {
                [self.keyboardView removeFromSuperview];
                TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                topVC.In_purchase = NO;
                topVC.backActionBlock = ^() {
                    [self dismissViewControllerAnimated:YES completion:NULL];
                };
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:topVC];
                [self presentViewController:nav animated:YES completion:nil];
                
            }
        }];
    }else{
        //        [MBProgressHUD showContent:@"操作太快喽!"];
    }
    
}
- (void)hide
{
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        
        
    } completion:^(BOOL finished)
     {
         [self.keyboardView removeFromSuperview];
     }];
}

- (void)addMicroVideoView
{
    CGFloat selfWidth  = self.view.bounds.size.width;
    CGFloat selfHeight = self.view.bounds.size.height;
    MicroVideoView *microVideoView = [[MicroVideoView alloc] initWithFrame:CGRectMake(0, selfHeight/3, selfWidth, selfHeight * 2/3)];
    microVideoView.delegate = self;
    [self.view addSubview:microVideoView];
}

- (void)touchUpDone:(NSString *)savePath
{
    NSError *err = nil;
    NSData* data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:savePath] options:NSDataReadingMappedIfSafe error:&err];
    //文件最大不超过28MB
    if(data.length < 28 * 1024 * 1024)
    {
        IMAMsg *msg = [IMAMsg msgWithVideoPath:savePath];
        [self sendMsg:msg];
    }
    else
    {
        [[HUDHelper sharedInstance] tipMessage:@"发送的文件过大"];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMAMsg *msg = [_messageList objectAtIndex:indexPath.row];
    
    return [msg heightInWidth:tableView.bounds.size.width inStyle:_conversation.type == TIM_GROUP] + 20;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_messageList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMAMsg *msg = [_messageList objectAtIndex:indexPath.row];
    UITableViewCell<TIMElemAbleCell> *cell = [msg tableView:tableView style:[_receiver isC2CType] ? TIMElemCell_C2C : TIMElemCell_Group];
    IMAUser *user = [[IMAUser alloc] initWithUserInfo:[msg.msg GetSenderProfile]];
    [cell configWith:msg withImage:_receiver.icon withUserId:user.userId withIndexPath:indexPath user:_receiver];
    return cell;
}

#pragma mark - 相机权限检测

- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

#pragma mark -


#pragma mark - 屏幕方向改变
- (BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return  UIInterfaceOrientationPortrait;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - notification
- (void)onTapPayImage {
    [self analyticsEvent2];
    [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
}

- (void)onTapPayVideo {
    [self analyticsEvent3];
    [[NSNotificationCenter defaultCenter] postNotificationName:BMHRefreshUserInfo object:nil];
}

- (void)tapMessageAvatar:(NSNotification *)notification {
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        return;
    }
    if (![_receiver.userId isEqualToString:@"10000"]) {
        IMAMsg *msg = notification.object;
        XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
        vc.userId = [msg isMineMsg] ? [[XLAccountManager shareInstance] model].Id : _receiver.userId;
        self.isenter = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - analyticsEvent
- (void)analyticsEvent1 {
    [MobClick event:@"click_videochat" attributes:@{@"userid" : [[XLAccountManager shareInstance] model].Id ?: @"", @"camgirlId" : _receiver.userId ?: @""}];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_message" action:@"click_videochat" userId:[[XLAccountManager shareInstance] model].Id camgirlId:_receiver.userId] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}

- (void)analyticsEvent2 {
    [MobClick event:@"click_redimg" attributes:@{@"userid" : [[XLAccountManager shareInstance] model].Id ?: @"", @"camgirlId" : _receiver.userId ?: @""}];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_message" action:@"click_redimg" userId:[[XLAccountManager shareInstance] model].Id camgirlId:_receiver.userId] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}

- (void)analyticsEvent3 {
    [MobClick event:@"click_redvideo" attributes:@{@"userid" : [[XLAccountManager shareInstance] model].Id ?: @"", @"camgirlId" : _receiver.userId ?: @""}];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_message" action:@"click_redvideo" userId:[[XLAccountManager shareInstance] model].Id camgirlId:_receiver.userId] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}

- (void)analyticsEvent4 {
    [MobClick event:@"click_videochaticon" attributes:@{@"userid" : [[XLAccountManager shareInstance] model].Id ?: @"", @"camgirlId" : _receiver.userId ?: @""}];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_message" action:@"click_videochaticon" userId:[[XLAccountManager shareInstance] model].Id camgirlId:_receiver.userId] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}

- (void)analyticsEvent5 {
    [MobClick event:@"click_gifticon" attributes:@{@"userid" : [[XLAccountManager shareInstance] model].Id ?: @"", @"camgirlId" : _receiver.userId ?: @""}];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_message" action:@"click_gifticon" userId:[[XLAccountManager shareInstance] model].Id camgirlId:_receiver.userId] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}

-(NSMutableArray *)mediaArray
{
    if(_mediaArray == nil)
    {
        _mediaArray = [[NSMutableArray alloc]init];
    }
    return _mediaArray;
}



-(void)getIsAnchorWithUserID:(NSString *)userID Complete:(void(^)(NSString * isAnchor))complete
{
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/api/v2/UserInfo/GetUserInfo" parameters:@{@"userId":userID} resultClass:[XLUserInfoModel class]] subscribeNext:^(id x) {
        //        NSDictionary * dict = (NSDictionary *)x;
        XLUserInfoModel * model = (XLUserInfoModel *)x;
        if(complete)
        {
            complete(SafeStr(model.IsAnchor));
        }
        
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        if(complete)
        {
            complete(@"0");
        }
    }];
}


@end
